package com.example.administrator.exkotlin.broadcast

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.administrator.exkotlin.R
import kotlinx.android.synthetic.main.activity_broad_cast.*

/**
 * 广播的例子
 * */
class BroadCastActivity : AppCompatActivity() {

    lateinit var mDynamicReciver: DynamicReciver
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_broad_cast)
        init()
        registe()
    }

    private fun init() {
        mDynamicReciver = DynamicReciver()

        btn_send_test01.setOnClickListener {
            sendTest01()
        }
    }

    //发送自定义广播
    private fun sendTest01() {
        val intent = Intent()
        intent.action = MyTestReceiver.MY_BROACAST_TEST_01
        intent.putExtra("test01", System.currentTimeMillis())
        //8.0系统之后，不允许静态注册的形式接收隐式广播因此在发送广播的时候要加上包名，变成显式广播
        intent.setPackage(packageName)
        sendBroadcast(intent)
    }

    private fun registe() {
        val intentFilter = IntentFilter()
        intentFilter.addAction(Intent.ACTION_TIME_TICK)
        registerReceiver(mDynamicReciver, intentFilter)


    }

    private fun unRegiste() {
        unregisterReceiver(mDynamicReciver)
    }

    inner class DynamicReciver : BroadcastReceiver() {

        override fun onReceive(context: Context?, intent: Intent?) {
            when (intent?.action) {
                Intent.ACTION_TIME_TICK -> {
                    Toast.makeText(context, "收到时间变化广播", Toast.LENGTH_SHORT).show()
                }
            }
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        unRegiste()
    }
}
